<template>
    <div>
        <Card dis-hover :bordered="false" class="ivu-mt-8">
            <Button
                v-hasC="{
                    name: 'rbac-role-agency-create',
                    flag: 'v1/rbac/role/agency-create',
                }"
                type="primary"
                @click="handleCreate((edit = true))"
            >新建角色</Button
            >
            <Row :gutter="40">
                <Col span="6">
                <List class="ivu-mt-16 listContent">
                    <ListItem
                        v-for="(item, index) in roleList"
                        :key="index"
                        :class="initIndex === item.id ? 'active' : null"
                        style="cursor: pointer;"
                    >
                        <div
                            @click="changeIndex(item, index)"
                            style="
                                    width: 300px;
                                    padding-left: 20px;
                                    box-sizing: border-box;
                                    height: 100%;
                                    display: flex;
                                    align-items: center;
                                "
                        >
                            {{ item.name }}
                        </div>
                        <template slot="action">
                            <li>
                                <a
                                    v-hasC="{
                                        name: 'rbac-role-agency-update',
                                        flag: 'v1/rbac/role/agency-update',
                                    }"
                                    :class="
                                        initIndex === item.id
                                            ? 'active'
                                            : null
                                    "
                                    @click="
                                        handleCreate((edit = false), item)
                                    "
                                >编辑</a
                                >
                            </li>
                            <li>
                                <a
                                    v-hasC="{
                                        name: 'rbac-role-agency-delete',
                                        flag: 'v1/rbac/role/agency-delete',
                                    }"
                                    :class="
                                        initIndex === item.id
                                            ? 'active'
                                            : null
                                    "
                                    @click="handleDelete(item)"
                                >删除</a
                                >
                            </li>
                            <li>
                                <a @click="copyRoleFun(item)">复制</a>
                            </li>
                        </template>
                    </ListItem>
                </List>
                </Col>
                <Col span="18">
                <h4 class="ivu-mt-8">
                    {{ isEdit.name }}
                    <Button
                        v-hasC="{
                            name: 'rbac-role-agency-permission',
                            flag: 'v1/rbac/role/agency-permission',
                        }"
                        class="ivu-fr"
                        type="primary"
                        @click="submit"
                        :loading="remarksloading"
                    >保存</Button
                    >
                </h4>
                <p>描述：{{ isEdit.desc }}</p>
                <Divider class="ivu-mt-8"></Divider>
                <div class="ivu-mt-16 ivu-mb-8">权限配置</div>
                <div style="max-height: 600px; overflow: auto;">
                    <tree-table :menu-data="rolePermissionList" :roledata="rolePermissionList" :level="1"/>
                    <!-- <Tree
                        class="role-permission-modal"
                        ref="roleTree"
                        :data="rolePermissionList"
                        multiple
                        show-checkbox
                        @on-check-change="handleSelectRoles"
                    ></Tree> -->
                </div>
                    <!-- <Form :model="formItem" :label-width="80">
            <FormItem label="业务">
              <span class="sky-color">线索/留言</span>

              <CheckboxGroup
                v-model="checkAllGroup"
                @on-change="checkAllGroupChange"
              >
                <Checkbox label="查看"></Checkbox>
                <Checkbox label="新增"></Checkbox>
                <Checkbox label="编辑"></Checkbox>
                <Checkbox label="回访"></Checkbox>
              </CheckboxGroup>
              <span class="sky-color">线索/客户录入</span>
              <CheckboxGroup
                v-model="checkAllGroup"
                @on-change="checkAllGroupChange"
              >
                <Checkbox label="查看"></Checkbox>
                <Checkbox label="新增"></Checkbox>
                <Checkbox label="回访"></Checkbox>
              </CheckboxGroup>
            </FormItem>
            <FormItem label="设置">
              <span class="sky-color">项目设置/权限/人员</span>
              <CheckboxGroup
                v-model="checkAllGroup"
                @on-change="checkAllGroupChange"
              >
                <Checkbox label="查看"></Checkbox>
                <Checkbox label="新增"></Checkbox>
                <Checkbox label="编辑"></Checkbox>
                <Checkbox label="回访"></Checkbox>
              </CheckboxGroup>
            </FormItem>
            <FormItem label="报表">
              <span class="sky-color">灯塔报表/回访报表</span>
              <CheckboxGroup
                v-model="checkAllGroup"
                @on-change="checkAllGroupChange"
              >
                <Checkbox label="查看"></Checkbox>
                <Checkbox label="新增"></Checkbox>
                <Checkbox label="编辑"></Checkbox>
                <Checkbox label="回访"></Checkbox>
              </CheckboxGroup>
            </FormItem>
          </Form> -->
                </Col>
            </Row>
        </Card>
        <Modal
            :mask-closable="false"
            title="患者列表-字段设置"
            v-model="drawerField"
            width="500"
        >
            <Table highlight-row :columns="columns1" :data="fieldList" border>
                <template slot="power" slot-scope="{ row }">
                    <CheckboxGroup>
                        <Checkbox :label="row.power[0]" disabled></Checkbox>
                        <Checkbox :label="row.power[1]"></Checkbox>
                    </CheckboxGroup>
                </template>
            </Table>
        </Modal>
        <Modal
            :mask-closable="false"
            :title="edit ? '新增角色' : '编辑角色'"
            v-model="editModal"
            width="500"
        >
            <Form
                :label-width="80"
                ref="form"
                :model="formParams"
                :rules="ruleValidate"
            >
                <FormItem label="名称" prop="name">
                    <Input placeholder="请输入名称" v-model="formParams.name" />
                </FormItem>
                <FormItem label="描述">
                    <Input
                        type="textarea"
                        :rows="3"
                        v-model="formParams.desc"
                    />
                </FormItem>
            </Form>
            <div slot="footer">
                <Button type="text" @click="editModal = false">取消</Button>
                <Button
                    type="primary"
                    :loading="remarksloading"
                    @click="handler"
                >确定</Button
                >
            </div>
        </Modal>
        <Modal v-model="copyModal" :title="copyNames">
            <span>请修改复制后的角色名称，避免重复</span>
            <Input v-model="copyValue" placeholder="请输入角色名称" />
            <div slot="footer">
                <Button @click="copyModal = false">取消</Button>
                <Button type="primary" @click="copyFun" :loading="copyLoading"
                >确定</Button
                >
            </div>
        </Modal>
    </div>
</template>
<script>
import {
    getRoleLists,
    addRoleLists,
    editRoleLists,
    deleteRoleLists,
    getRoleInfo,
    rolePreSets,
    copyRole,
} from '@/api/TApi/index.js';
import treeTable from './treetable';
import { mapState, mapActions, mapMutations } from 'vuex';
export default {
    name: 'diagnosis',
    components: {treeTable},
    computed: {
        ...mapState('power/power', ['modules', 'menuIds','actionIds']),
        copyNames() {
            return '是否确认复制' + this.copyName.name + '该角色?';
        },
    },
    data() {
        return {
            copyValue: '',
            copyModal: false,
            copyLoading: false,

            copyName: '',

            formParams: {
                name: '',
                desc: '',
            },
            ruleValidate: {
                name: {
                    required: true,
                    message: '请输入名称',
                    trigger: 'blur',
                },
            },
            roleList: [],
            remarksloading: false,
            initIndex: '',
            isEdit: '',
            edit: true,
            editModal: false,
            drawerField: false,
            indeterminate: true,
            checkAll: false,
            checkAllGroup: ['查看', '新增'],
            modal: false,
            rolePermissionList: [],
            formItem: {
                input: '',
                explain: '',
                switch: true,
            },
            formItem1: {
                interset: '',
            },
            columns1: [
                {
                    title: '名称',
                    key: 'name',
                },
                {
                    title: '类型',
                    key: 'type',
                },
                {
                    title: '权限',
                    slot: 'power',
                    width: 180,
                },
            ],
            // 设置权限的集合
            selectPermissonList: [],
            fieldList: [
                {
                    name: '姓名',
                    type: '文本类型',
                    power: ['只读', '读写'],
                },
                {
                    name: '手机号',
                    type: '电话类型',
                    power: ['只读', '读写'],
                },
                {
                    name: '性别',
                    type: '单选类型',
                    power: ['只读', '读写'],
                },
                {
                    name: '病种',
                    type: '关联关系',
                    power: ['只读', '读写'],
                },
                {
                    name: '下次回访时间',
                    type: '日期类型',
                    power: ['只读', '读写'],
                },
                {
                    name: '下次预约时间',
                    type: '日期类型',
                    power: ['只读', '读写'],
                },
            ],
            mymenuIds: [],// 角色菜单
            myactionIds: [],// 角色动作
            mymoduleIds: [],// 角色模块
        };
    },
    mounted() {
        this.init();
    },
    methods: {
        ...mapActions('power/power', ['modulesAsync', 'menuIdsAsync','actionIdsAsync']),
      
        copyRoleFun(item) {
            this.copyName = item;
            this.copyValue = item.name;
            this.copyModal = true;
        },
        copyFun() {
            let flag = this.roleList.find((ee) => {
                return ee.name === this.copyValue; 
            });
            if (flag) {
                this.$Message.warning('当前角色名称已存在');
            } else {
                this.copyLoading = true;
                copyRole({
                    id: this.copyName.id,
                    type: this.copyName.type,
                    role_name: this.copyValue,
                })
                    .then((res) => {
                        this.copyLoading = false;
                        this.$Message.success('复制成功');
                        this.copyModal = false;
                        this.init();
                    })
                    .catch((err) => {
                        this.copyLoading = false;
                    });
            }
        },
      
        //   init
        async init() {
            await this._getRoleList();
            await this._getRoleInfo(this.initIndex);
            
        },
        // 选择权限此处treeselect方法注释暂不使用《Tree》
        handleSelectRoles(value) {
            // console.log(value);
            let checklist = this.$refs[
                'roleTree'
            ].getCheckedAndIndeterminateNodes();
            this.selectPermissonList = [];
            checklist.forEach((item) => {
                let resList = {};
                resList.permission_id = item.value;
                resList.permission_type = item.permission_type;
                this.selectPermissonList.push(resList);
            });
        },

        //   新增/编辑点击确定
        handler() {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    this.remarksloading = true;
                    let title = '';
                    let func;
                    let params = {
                        name: this.formParams.name,
                        desc: this.formParams.desc,
                    };
                    switch (this.edit) {
                        case true:
                            {
                                title = '新增';
                                func = addRoleLists;
                            }
                            break;
                        case false:
                            {
                                title = '编辑';
                                params.id = this.isEdit.id;
                                func = editRoleLists;
                            }
                            break;
                    }
                    func(params).then((res) => {
                        this.$Message.success(`${title}成功`);
                        this.editModal = false;
                        this.init();
                        setTimeout(() => {
                            this.remarksloading = false;
                        },500);
                    }).catch(() => {
                        this.remarksloading = false;
                    });
                }
            });
        },
        // 初始化列表
        _getRoleList() {
            return new Promise((resolve, reject) => {
                getRoleLists().then((res) => {
                    if (res.length) {
                        this.roleList = res;
                        this.initIndex = res[0].id;
                        this.isEdit = res[0];
                        resolve();
                    } else {
                        this.roleList = [];
                        this.isEdit = {};
                        reject();
                    }
                });
            });
        },
        // 初始化权限配置liebia
        _getRoleInfo(id) {
            this.myactionIds = [];
            this.mymenuIds = [];
            this.mymoduleIds = [];
            return new Promise((resolve) => {
                getRoleInfo({
                    id,
                }).then((res) => {
                    this.rolePermissionList = res.auth;
                    this.$nextTick(() => {
                    this.refreshgrops(res.auth);
                    this.modulesAsync(this.mymoduleIds);
                    this.menuIdsAsync(this.mymenuIds);
                    this.actionIdsAsync(this.myactionIds);
                    });
                   
                    // console.log(this.mymoduleIds,this.mymenuIds,this.myactionIds,'se1111111111');
                    resolve();
                });
            });
        },
        // 获取回显渲染及数据处理
        refreshgrops(item){
            item.forEach(el => {
                if(!el.checked && el.half_checked){
                    this.$set(el, 'isIndeterminate', true);
                }
                // console.log(el.checked,'el');
                if(el.checked === true && el.permission_type === 2){
                    this.myactionIds.push(el.value);
                }else if((el.checked == true || el.isIndeterminate) && el.permission_type === 1){
                    this.mymenuIds.push(el.value);
                }else if((el.checked == true || el.isIndeterminate) && el.permission_type === 0){
                    this.mymoduleIds.push(el.value);
                }
                if(el.children){
                    this.refreshgrops(el.children);
                }
            });
        // }
        },
        submit() {
            // console.log(this.modules,'this.mod模块');
            // console.log(this.menuIds,'this.mod菜单');
            // console.log(this.actionIds,'this.mod动作');
            // 提交数据处理，vuex存储数据
            let sendData = {};      
            sendData.id = this.isEdit.id;
            sendData.menu_ids = this.menuIds.length > 0 ? this.menuIds.join(',') : '';
            sendData.action_ids =
            this.actionIds.length > 0 ? this.actionIds.join(',') : '';
            sendData.module_ids =
            this.modules.length > 0 ? this.modules.join(',') : '';
            this.remarksloading = true;
            rolePreSets(sendData).then((res) => {
                this.$Message.success('设置成功');
                this.remarksloading = false;
            }).catch(() => {
                this.remarksloading = false;
            });
        },
        changeIndex(item, index) {
            this.initIndex = item.id;
            this.isEdit = item;
            this._getRoleInfo(item.id);
        },
        checkAllGroupChange(data) {
            if (data.length === 4) {
                this.indeterminate = false;
                this.checkAll = true;
            } else if (data.length > 0) {
                this.indeterminate = true;
                this.checkAll = false;
            } else {
                this.indeterminate = false;
                this.checkAll = false;
            }
        },
        handleCreate(type, item) {
            this.$refs.form.resetFields();
            this.formParams.desc = '';
            switch (type) {
                case true:
                    {
                        //
                    }
                    break;
                case false:
                    {
                        this.initIndex = item.id;
                        this.isEdit = item;
                        this._getRoleInfo(item.id);
                        this.formParams.name = item.name;
                        this.formParams.desc = item.desc;
                    }
                    break;
            }
            this.editModal = true;
        },
        handleDelete(item) {
            this.initIndex = item.id;
            this.isEdit = item;
            this._getRoleInfo(item.id);
            this.$Modal.confirm({
                title: '操作提示',
                content: '确认删除该角色吗？',
                onOk: () => {
                    deleteRoleLists({
                        id: item.id,
                    }).then((res) => {
                        this.$Message.success('删除成功');
                        this.init();
                    });
                },
            });
        },
    },
};
</script>
<style scoped>
.sky-color {
    color: #888;
}

/deep/.ivu-list-item-action {
    margin-left: 0 !important;
}

/deep/.ivu-list-item {
    align-items: center !important;
    padding: 0 !important;
    height: 40px !important;
}

.active {
    background-color: #55b6ec;
    color: white;
}

.listContent {
    max-height: 600px;
    overflow: auto;
}

/*滚动条样式*/
.listContent::-webkit-scrollbar {
    width: 4px;
    height: 4px;
}

.listContent::-webkit-scrollbar-thumb {
    border-radius: 10px;
    -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    background: rgba(0, 0, 0, 0.2);
}

.listContent::-webkit-scrollbar-track {
    -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    border-radius: 0;
    background: rgba(0, 0, 0, 0.1);
}
</style>
